<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" :inline="true" v-show="showSearch" label-width="100px">
      <el-form-item label="设备模板名称" prop="devMName">
        <el-input
          v-model="queryParams.devMName"
          placeholder="请输入设备模板名称"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="状态" prop="status">
        <el-select v-model="queryParams.status" placeholder="请选择状态" clearable size="small">
          <el-option
            v-for="dict in dict.type.sys_normal_disable"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="类型" prop="type">
        <el-select v-model="queryParams.type" placeholder="请选择类型" clearable size="small">
          <el-option
            v-for="dict in dict.type.device_mould_type"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item>
	    <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['erh-iot:device_mould:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="info"
          plain
          icon="el-icon-sort"
          size="mini"
          @click="toggleExpandAll"
        >展开/折叠</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table
      v-loading="loading"
      :data="device_mouldList"
      row-key="devMId"
      v-if="refreshTable"
      :default-expand-all="isExpandAll"
      :tree-props="{children: 'children', hasChildren: 'hasChildren'}"
    >
      <el-table-column label="设备模板名称" align="left" prop="devMName" />
      <el-table-column label="设备模板代码" align="center" prop="devMCode" />
      <el-table-column label="状态" align="center" prop="status">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.sys_normal_disable" :value="scope.row.status"/>
        </template>
      </el-table-column>
      <el-table-column label="类型" align="center" prop="type">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.device_mould_type" :value="scope.row.type"/>
        </template>
      </el-table-column>
      <el-table-column label="检测数据存储表" align="center" prop="dataTable">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.device_mould_data_table" :value="scope.row.dataTable"/>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['erh-iot:device_mould:edit']"
          >修改</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-plus"
            @click="handleAdd(scope.row)"
            v-hasPermi="['erh-iot:device_mould:add']"
          >新增</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['erh-iot:device_mould:remove']"
          >删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 添加或修改设备模板对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="1200px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="120px">
        <el-form-item label="归属" prop="prevId">
          <treeselect v-model="form.prevId" :options="device_mouldOptions" :normalizer="normalizer" placeholder="请选择${comment}" />
        </el-form-item>
        <el-form-item label="设备代码" prop="devMCode">
          <el-input v-model="form.devMCode" placeholder="请输入设备模板代码" />
        </el-form-item>
        <el-form-item label="设备名称" prop="devMName">
          <el-input v-model="form.devMName" placeholder="请输入设备模板名称" />
        </el-form-item>
        <el-form-item label="状态">
          <el-radio-group v-model="form.status">
            <el-radio
              v-for="dict in dict.type.sys_normal_disable"
              :key="dict.value"
              :label="dict.value"
            >{{dict.label}}</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="类型" prop="type">
          <el-select v-model="form.type" placeholder="请选择类型">
            <el-option
              v-for="dict in dict.type.device_mould_type"
              :key="dict.value"
              :label="dict.label"
              :value="dict.value"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="单位" prop="unit">
          <el-select v-model="form.unit" placeholder="请选择单位">
            <el-option
              v-for="dict in dict.type.device_mould_unit"
              :key="dict.value"
              :label="dict.label"
              :value="dict.value"
            ></el-option>
          </el-select>
        </el-form-item>
<!--
        <el-form-item label="检测数据存储表" prop="dataTable">
          <el-select v-model="form.dataTable" placeholder="请选择检测数据存储表">
            <el-option
              v-for="dict in dict.type.device_mould_data_table"
              :key="dict.value"
              :label="dict.label"
              :value="dict.value"
            ></el-option>
          </el-select>
        </el-form-item>
-->

        <el-row>
          <el-col :span="12">
            <el-form-item label="设备接口" prop="iotDeviceClass">
              <el-select v-model="form.iotDeviceClass" placeholder="请选择设备接口" @change="onDeviceSelectChange">
                <el-option
                  v-for="clz in deviceClasses"
                  :key="clz.service"
                  :label="clz.name"
                  :value="clz.service"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="接口创建模式" prop="iotDeviceDiType">
              <el-select v-model="form.iotDeviceDiType" placeholder="请选择接口创建模式">
                <el-option
                  v-for="dict in dict.type.device_mould_di_type"
                  :key="dict.value"
                  :label="dict.label"
                  :value="dict.value"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="协议规则接口" prop="iotRuleClass">
              <el-select v-model="form.iotRuleClass" placeholder="请选择协议规则接口" @change="onRuleSelectChange">
                <el-option
                  v-for="clz in ruleClasses"
                  :key="clz.service"
                  :label="clz.name"
                  :value="clz.service"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="接口创建模式" prop="iotRuleDiType">
              <el-select v-model="form.iotRuleDiType" placeholder="请选择接口创建模式">
                <el-option
                  v-for="dict in dict.type.device_mould_di_type"
                  :key="dict.value"
                  :label="dict.label"
                  :value="dict.value"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="输出接口" prop="iotOutputClass">
              <el-select v-model="form.iotOutputClass" placeholder="请选择输出接口" @change="onOutputSelectChange">
                <el-option
                  v-for="clz in outputClasses"
                  :key="clz.service"
                  :label="clz.name"
                  :value="clz.service"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="接口创建模式" prop="iotOutputDiType">
              <el-select v-model="form.iotOutputDiType" placeholder="请选择接口创建模式">
                <el-option
                  v-for="dict in dict.type.device_mould_di_type"
                  :key="dict.value"
                  :label="dict.label"
                  :value="dict.value"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="存储接口" prop="iotStoreClass">
              <el-select v-model="form.iotStoreClass" placeholder="请选择存储接口" @change="onStoreSelectChange">
                <el-option
                  v-for="clz in storeClasses"
                  :key="clz.service"
                  :label="clz.name"
                  :value="clz.service"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="接口创建模式" prop="iotStoreDiType">
              <el-select v-model="form.iotStoreDiType" placeholder="请选择接口创建模式">
                <el-option
                  v-for="dict in dict.type.device_mould_di_type"
                  :key="dict.value"
                  :label="dict.label"
                  :value="dict.value"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-divider content-position="center">设备属性模板信息</el-divider>
        <el-row :gutter="10" class="mb8">
          <el-col :span="1.5">
            <el-button type="primary" icon="el-icon-plus" size="mini" @click="handleAddDeviceMouldProperty">添加</el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button type="danger" icon="el-icon-delete" size="mini" @click="handleDeleteDeviceMouldProperty">删除</el-button>
          </el-col>
        </el-row>
        <el-table :data="deviceMouldPropertyList" :row-class-name="rowDeviceMouldPropertyIndex" @selection-change="handleDeviceMouldPropertySelectionChange" ref="deviceMouldProperty">
          <el-table-column type="selection" width="50" align="center" />
          <el-table-column label="序号" align="center" prop="index" width="50"/>
          <el-table-column label="属性类型" prop="type" width="100">
            <template slot-scope="scope">
              <el-input v-model="scope.row.type" placeholder="请输入属性类型" />
            </template>
          </el-table-column>
          <el-table-column label="属性码" prop="code" width="100">
            <template slot-scope="scope">
              <el-input v-model="scope.row.code" placeholder="请输入属性码" />
            </template>
          </el-table-column>
          <el-table-column label="属性名称" prop="name" width="100">
            <template slot-scope="scope">
              <el-input v-model="scope.row.name" placeholder="请输入属性名称" />
            </template>
          </el-table-column>
          <el-table-column label="缺省属性值" prop="property">
            <template slot-scope="scope">
              <el-input v-model="scope.row.property" :type="DMPCType(scope.row.code)" :rows="DMPRows(scope.row.code)" placeholder="请输入缺省属性值" />
            </template>
          </el-table-column>
          <el-table-column label="值类型" prop="valueType" width="100">
            <template slot-scope="scope">
              <el-input v-model="scope.row.valueType" placeholder="请输入值类型" />
            </template>
          </el-table-column>
        </el-table>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listDevice_mould, getDevice_mould, delDevice_mould, addDevice_mould, updateDevice_mould, exportDevice_mould, getAllClasses } from "@/api/business/device_mould";
import Treeselect from "@riophae/vue-treeselect";
import "@riophae/vue-treeselect/dist/vue-treeselect.css";

export default {
  name: "Device_mould",
  dicts: ['sys_normal_disable', 'device_mould_type', 'device_mould_unit', 'device_mould_data_table', 'device_mould_di_type'],
  components: {
    Treeselect
  },
  data() {
    return {
      // 遮罩层
      loading: true,
      // 子表选中数据
      checkedDeviceMouldProperty: [],
      // 显示搜索条件
      showSearch: true,
      // 是否展开，默认全部折叠
      isExpandAll: true,
      // 重新渲染表格状态
      refreshTable: true,
      // 设备模板表格数据
      device_mouldList: [],
      // 设备模板树选项
      device_mouldOptions: [],
      // 设备属性模板表格数据
      deviceMouldPropertyList: [],
      // 设备接口类数据
      deviceClasses: [],
      // 协议规则接口类数据
      ruleClasses: [],
      // 输出接口类数据
      outputClasses: [],
      // 存储接口类数据
      storeClasses: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        prevId: null,
        devMCode: null,
        devMName: null,
        devMLevel: null,
        status: null,
        type: null,
        unit: null,
        dataTable: null,
        price: null,
        photo: null
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        devMCode: [
          { required: true, message: "设备模板代码不能为空", trigger: "blur" }
        ],
        devMName: [
          { required: true, message: "设备模板名称不能为空", trigger: "blur" }
        ],
        devMLevel: [
          { required: true, message: "级别不能为空", trigger: "blur" }
        ],
        createId: [
          { required: true, message: "创建者ID不能为空", trigger: "blur" }
        ],
        createBy: [
          { required: true, message: "创建者不能为空", trigger: "blur" }
        ],
      }
    };
  },
  created() {
    this.getList();
  },
  methods: {
    SyncProperty2IOT(iotpl)
    {
      for(let i = 0; i<this.deviceMouldPropertyList.length;)
      {
        let p = iotpl.find(item => (item.type===this.deviceMouldPropertyList[i].type&&item.code===this.deviceMouldPropertyList[i].code));
        if(p!==undefined)
        {
          if(!(!this.deviceMouldPropertyList[i].property || this.deviceMouldPropertyList[i].property.length === 0))
            p.property = this.deviceMouldPropertyList[i].property;
          this.deviceMouldPropertyList.splice(i, 1);
        }else
          i++;
      }
    },
    SyncIOT2Property(iotpl)
    {
      for(let i = 0; i<iotpl.length; i++)
      {
        let p = this.deviceMouldPropertyList.find(item => (item.type===iotpl[i].type&&item.code===iotpl[i].code));
        if(p!==undefined)
        {
          if(!(!iotpl[i].property || iotpl[i].property.length === 0))
            p.property = iotpl[i].property;
        }else
          this.deviceMouldPropertyList.push(iotpl[i]);
      }
    },
    onDeviceSelectChange(event)
    {
      let oldObj = this.deviceClasses.find(item => item.service === this.oldIot.iotDeviceClass);
      if(oldObj !== undefined)
        this.SyncProperty2IOT(oldObj.property);
      let newObj = this.deviceClasses.find(item => item.service === this.form.iotDeviceClass);
      if(newObj !== undefined)
        this.SyncIOT2Property(newObj.property);
      
      this.oldIot.iotDeviceClass = this.form.iotDeviceClass;
    },
    onRuleSelectChange(event)
    {
      let oldObj = this.ruleClasses.find(item => item.service === this.oldIot.iotRuleClass);
      if(oldObj !== undefined)
        this.SyncProperty2IOT(oldObj.property);
      let newObj = this.ruleClasses.find(item => item.service === this.form.iotRuleClass);
      if(newObj !== undefined)
        this.SyncIOT2Property(newObj.property);
      
      this.oldIot.iotRuleClass = this.form.iotRuleClass;
    },
    onOutputSelectChange(event)
    {
      let oldObj = this.outputClasses.find(item => item.service === this.oldIot.iotOutputClass);
      if(oldObj !== undefined)
        this.SyncProperty2IOT(oldObj.property);
      let newObj = this.outputClasses.find(item => item.service === this.form.iotOutputClass);
      if(newObj !== undefined)
        this.SyncIOT2Property(newObj.property);
      
      this.oldIot.iotOutputClass = this.form.iotOutputClass;
    },
    onStoreSelectChange(event)
    {
      let oldObj = this.storeClasses.find(item => item.service === this.oldIot.iotStoreClass);
      if(oldObj !== undefined)
        this.SyncProperty2IOT(oldObj.property);
      let newObj = this.storeClasses.find(item => item.service === this.form.iotStoreClass);
      if(newObj !== undefined)
        this.SyncIOT2Property(newObj.property);
      
      this.oldIot.iotStoreClass = this.form.iotStoreClass;
    },
    DMPCType(code)
    {
      if ( code == "rule_script" )
        return 'textarea';
      else
        return 'text';
    },
    DMPRows(code)
    {
      if ( code == "rule_script" )
        return '20';
      else
        return '1';
    },
    /** 查询设备模板列表 */
    getList() {
      this.loading = true;
      listDevice_mould(this.queryParams).then(response => {
        this.device_mouldList = this.handleTree(response.data, "devMId", "prevId");
        this.loading = false;
      });
    },
    /** 转换设备模板数据结构 */
    normalizer(node) {
      if (node.children && !node.children.length) {
        delete node.children;
      }
      return {
        id: node.devMId,
        label: node.devMName,
        children: node.children
      };
    },
	/** 查询设备模板下拉树结构 */
    getTreeselect() {
      listDevice_mould().then(response => {
        this.device_mouldOptions = [];
        const data = { devMId: 0, devMName: '顶级节点', children: [] };
        data.children = this.handleTree(response.data, "devMId", "prevId");
        this.device_mouldOptions.push(data);
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        devMId: null,
        prevId: null,
        devMCode: null,
        devMName: null,
        devMLevel: '0',
        status: "0",

        delFlag: null,
        type: null,
        unit: null,
        createTime: null,
        createId: null,
        createBy: null,
        updateTime: null,
        updateId: null,
        updateBy: null,
        closeTime: null,
        closeId: null,
        dataTable: null,
        price: null,
        photo: null,
        iotDeviceClass: null,
	iotDeviceDiType: null,
        iotRuleClass: null,
	iotRuleDiType: null,
        iotOutputClass: null,
	iotOutputDiType: null,
        iotStoreClass: null,
	iotStoreDiType: null,
      };
      this.oldIot = {
        iotDeviceClass: null,
        iotRuleClass: null,
        iotOutputClass: null,
        iotStoreClass: null
      };
      
      this.deviceMouldPropertyList = [];
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    /** 新增按钮操作 */
    handleAdd(row) {
      this.reset();
      this.getTreeselect();
      if (row != null && row.devMId) {
        this.form.prevId = row.devMId;
      } else {
        this.form.prevId = 0;
      }
      this.open = true;
      this.title = "添加设备模板";
      getAllClasses().then(response => {
        this.deviceClasses = response.data.device;
        this.ruleClasses = response.data.rule;
        this.outputClasses = response.data.output;
        this.storeClasses = response.data.store;
      });
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      this.getTreeselect();
      if (row != null) {
        this.form.prevId = row.devMId;
      }
      getDevice_mould(row.devMId).then(response => {
        this.form = response.data;
        this.oldIot = {
          iotDeviceClass: this.form.iotDeviceClass,
          iotRuleClass: this.form.iotRuleClass,
          iotOutputClass: this.form.iotOutputClass,
          iotStoreClass: this.form.iotStoreClass
        };
        this.deviceMouldPropertyList = response.data.deviceMouldPropertyList;
        this.open = true;
        this.title = "修改设备模板";
      });
      getAllClasses().then(response => {
        this.deviceClasses = response.data.device;
        this.ruleClasses = response.data.rule;
        this.outputClasses = response.data.output;
        this.storeClasses = response.data.store;
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          this.form.deviceMouldPropertyList = this.deviceMouldPropertyList;
          if (this.form.devMId != null) {
            updateDevice_mould(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addDevice_mould(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      this.$modal.confirm('是否确认删除设备模板编号为"' + row.devMId + '"的数据项？').then(function() {
        return delDevice_mould(row.devMId);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {});
    },
	/** 设备属性模板序号 */
    rowDeviceMouldPropertyIndex({ row, rowIndex }) {
      row.index = rowIndex + 1;
    },
    /** 设备属性模板添加按钮操作 */
    handleAddDeviceMouldProperty() {
      let obj = {};
      obj.type = "";
      obj.code = "";
      obj.name = "";
      obj.property = "";
      obj.valueType = "";
      obj.isNull = "";
      obj.sort = "";
      obj.remark = "";
      this.deviceMouldPropertyList.push(obj);
    },
    /** 设备属性模板删除按钮操作 */
    handleDeleteDeviceMouldProperty() {
      if (this.checkedDeviceMouldProperty.length == 0) {
        this.$modal.msgError("请先选择要删除的设备属性模板数据");
      } else {
        const deviceMouldPropertyList = this.deviceMouldPropertyList;
        const checkedDeviceMouldProperty = this.checkedDeviceMouldProperty;
        this.deviceMouldPropertyList = deviceMouldPropertyList.filter(function(item) {
          return checkedDeviceMouldProperty.indexOf(item.index) == -1
        });
      }
    },
    /** 复选框选中数据 */
    handleDeviceMouldPropertySelectionChange(selection) {
      this.checkedDeviceMouldProperty = selection.map(item => item.index)
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('device/device_mould/export', {
        ...this.queryParams
      }, `device_mould_${new Date().getTime()}.xlsx`)
    },
    /** 展开/折叠操作 */
    toggleExpandAll() {
      this.refreshTable = false;
      this.isExpandAll = !this.isExpandAll;
      this.$nextTick(() => {
        this.refreshTable = true;
    });
    },
  }
};
</script>
